package com.baizhi.service.impl;

import com.baizhi.dao.CategoryDao;
import com.baizhi.entity.Category;
import com.baizhi.po.CategoriesPO;
import com.baizhi.po.QueryCategoriesPO;
import com.baizhi.service.CategoryService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * 分类(Category)表服务实现类
 *
 * @author makejava
 * @since 2021-09-26 14:21:16
 */
@Transactional
@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, Category> implements CategoryService {

    @Autowired
    private CategoryDao categoryDao;

    @Override
    public List<QueryCategoriesPO> queryAll() {
        //条件
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        //判断删除为null,说明就是没有删除
        queryWrapper.isNull(Category::getDeletedAt);
        //判断为一级类别
        queryWrapper.isNull(Category::getParentId);
        //获得所有一级的类别
        List<Category> categories = categoryDao.selectList(queryWrapper);
        //创建集合存放QueryCategoriesPO
        ArrayList<QueryCategoriesPO> objects = new ArrayList<>();
        //遍历根据一级类别id获取对应的二级类别
        for (Category category : categories) {
            //每次遍历一次就是一次一级类别
            QueryCategoriesPO queryCategoriesPO = new QueryCategoriesPO();
            BeanUtils.copyProperties(category, queryCategoriesPO);
            LambdaQueryWrapper<Category> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.eq(Category::getParentId, category.getId());
            queryWrapper1.isNull(Category::getDeletedAt);
            List<Category> categories1 = categoryDao.selectList(queryWrapper1);
            List<CategoriesPO> categoriesPOS = new ArrayList<>();
            for (Category category1 : categories1) {
                CategoriesPO categoriesPO = new CategoriesPO();
                BeanUtils.copyProperties(category1, categoriesPO);
                categoriesPOS.add(categoriesPO);
            }
            queryCategoriesPO.setChildren(categoriesPOS);
            objects.add(queryCategoriesPO);
        }
        return objects;
    }

    @Override
    public CategoriesPO queryById(Integer id) {
        Category category = categoryDao.selectById(id);
        if (category.getDeletedAt() != null) {
            throw new RuntimeException("该标签已经删除");
        }
        CategoriesPO categoriesPO = new CategoriesPO();
        BeanUtils.copyProperties(category, categoriesPO);
        return categoriesPO;
    }
}

